let domTRarr=[]
let nodeActive = null
let currentSeleRow = 0
let resData = null

$NG.AllReady(function (
	page,
	{ useDataIndexChange, useUpdateRow, useUpdateRows, useValuesChange,useClick }
) {
	// 编辑页面逻辑
	const mstform = $NG.getCmpApi("p_form_integrated_apply_m");
	const grid1 = $NG.getCmpApi("p_form_integrated_apply_d1");
	const grid2 = $NG.getCmpApi("p_form_integrated_apply_d2");
	const getItemValue = (itemName) => mstform.getItem(itemName).getValue();
	/**
	 *@default: 初始化
	 */

    //  $NG
    //  .getCmpApi("p_form_integrated_apply_m")
    //  .getItem("u_bus_no")
    //  .getRef()
    //  .click(()=>{
    //     console.log(`被点击了`);
    //  });
    $NG.updateUI((updater, state) => {
        updater.form.p_form_integrated_apply_m.u_bus_no.setProps({
            onDoubleClick() {
        console.log(`被点击了`);
               onT()
            },
        });
    });
	if ($NG.getCmpApi("p_form_integrated_apply_m")) {
		getPtInfoByPhid();
	}
	/**
	 *@license: 	 //表头字段变化逻辑END	//表头字段变化逻辑BEGIN
	 */
	useValuesChange(({ args }) => {
		getPtInfoByPhid();
	}, "p_form_integrated_apply_m.phid_pc");
	/**
	 *@license: 	 //表头字段变化逻辑END	//表头字段变化逻辑BEGIN
	 */
	useValuesChange(({ args, instance }) => {
		console.log("args111", args);
		calcCostRedRate();
	}, "p_form_integrated_apply_m.u_pur_amt");
	/**
	 *@license:设备物资表 计算
	 */

	useUpdateRows(({ args }) => {
		console.log(args[0], "args");
		let sumAmt1 = 0;
		let sumAmt2 = 0;
		let sumAmt3 = 0;
		let sumAmt4 = 0;
		let rows = args[0];
		rows.forEach((row) => {
			if (row.u_target_prc && row.u_qty && row.u_prc && row.u_pre_sale_amt) {
				sumAmt1 += calcTargetAmt(row.u_target_prc, row.u_qty); //  目标价格 *数量 = 目标价格金额;
				sumAmt2 += calcMarketAmt(row.u_prc, row.u_qty); //  市场价格 *数量 = 市场平均金额;
				sumAmt3 += calcPreSaleAmt(row.u_pre_sale_amt, row.u_qty); //  市场价格 *数量 = 售前议价金额;
				sumAmt4 = calcCostRedRate();
			}

			//汇总赋值
			$NG.updateState((updater) => {
				updater.data.p_form_integrated_apply_m.setProps({
					u_tar_amt: sumAmt1,
					u_ave_amt: sumAmt2,
					u_sqyj_amt: sumAmt3,
					u_cost_red_rate: sumAmt4,
				});
			});
		});
		// row.u_qty; //数量
		// row.u_target_prc; //目标价格
		// row.u_pre_sale_amt; //售前议价结果
		// row.u_pur_prc; //最终采购价
		// row.u_prc; //市场价
	}, "p_form_integrated_apply_d1");

	/**
	 *@license:分包明细表 计算
	 */
	useUpdateRows(({ args }) => {
		console.log(args[0], "分包明细表 计算");
		// {
		//     "checked": true,
		//     "u_qty": 1111,数量
		//     "u_prc": 2222,市场价
		//     "u_tar_prc": 33333,目标价格
		//     "u_bar_prc": 44444,议价结果
		//     "u_fb_prc": 555555,最终分包价格
		//     "u_budget_cost": Doub
		// }

		let sumAmt1 = 0;
		let sumAmt2 = 0;
		let sumAmt3 = 0;
		let sumAmt4 = 0;
		let rows = args[0];
		rows.forEach((row) => {
			if (row.u_tar_prc && row.u_qty && row.u_prc && row.u_bar_prc) {
				sumAmt1 += calcTargetAmt(row.u_tar_prc, row.u_qty); //  目标价格 *数量 = 目标价格金额;
				sumAmt2 += calcMarketAmt(row.u_prc, row.u_qty); //  市场价格 *数量 = 市场平均金额;
				sumAmt3 += calcPreSaleAmt(row.u_bar_prc, row.u_qty); //  市场价格 *数量 = 售前议价金额;
				sumAmt4 = calcCostRedRate();
			}

			//汇总赋值
			$NG.updateState((updater) => {
				updater.data.p_form_integrated_apply_m.setProps({
					u_tar_amt: sumAmt1,
					u_ave_amt: sumAmt2,
					u_sqyj_amt: sumAmt3,
					u_cost_red_rate: sumAmt4,
				});
			});
		});
		// row.u_qty; //数量
		// row.u_target_prc; //目标价格
		// row.u_pre_sale_amt; //售前议价结果
		// row.u_pur_prc; //最终采购价
		// row.u_prc; //市场价
	}, "p_form_integrated_apply_d2");
	/**
	 *@function:带出项目信息
	 */
	function getPtInfoByPhid() {
		if (mstform.getItem("phid_pc").getValue()) {
			$NG.execServer(
				"getPtInfoByPhid",
				{ phid: mstform.getItem("phid_pc").getValue() },
				function (res) {
					const datas = JSON.parse(res.data)[0].extendObjects;
					console.log(datas, "datas");
					//帮助字段赋值
					$NG.updateState((updater) => {
						updater.data.p_form_integrated_apply_m.setProps({
							// u_supply_att: datas.u_supply_att, //计划完工日期
							// u_supply_name: datas.u_supply_name, //计划竣工日期
							bill_no: datas.pc_no, //项目编码
							phid_org: {
								//事业部or组织
								value: datas.phid_org_phid,
								label: datas.phid_org_name,
							},
							u_regional_center: {
								//区域中心
								value: datas.regional_center_phid,
								label: datas.regional_center_name,
							},
							u_product_line: {
								//产品线
								value: datas.midwife_phid,
								label: datas.midwife_name,
							},
						});
					});
				}
			);
		}
	}

	/**
	 *@function:目标价格金额 计算
	 */
	function calcTargetAmt(targePrice, num) {
		return targePrice * num;
	}

	/**
	 *@function:市场平均金额 计算
	 */

	function calcMarketAmt(targePrice, num) {
		return targePrice * num;
	}
	/**
	 *@function:售前议价金额 计算
	 */
	function calcPreSaleAmt(targePrice, num) {
		return targePrice * num;
	}

	/**
	 *@function:降成本率 计算
	 */
	function calcCostRedRate() {
		// 获取值并校验
		const sqyjAmt = parseFloat(getItemValue("u_sqyj_amt")) || 0; // 售前议价金额
		const purAmt = parseFloat(getItemValue("u_pur_amt")) || 0; // 最终采购价格

		// 检查售前议价金额是否为 0
		if (sqyjAmt === 0) {
			console.error("售前议价金额为 0 或无效，无法计算。");
		} else {
			// 计算差额百分比
			const percentageDiff = (sqyjAmt - purAmt) / sqyjAmt;
			console.log("差额百分比：", percentageDiff);

			// 如果需要输出百分比格式
			const percentageFormatted = (percentageDiff * 100).toFixed(2);
			console.log("格式化结果：", percentageFormatted + "%");

			$NG.updateState((updater) => {
				updater.data.p_form_integrated_apply_m.setProps({
					u_cost_red_rate: percentageFormatted,
				});
			});
			return percentageFormatted + "%";
		}
	}

	/**
	 *@function:损失率 计算
	 */

	function calcLossRate() {
		// 获取值并校验
		const sqyjAmt = parseFloat(getItemValue("u_sqyj_amt")) || 0; // 售前议价金额
		const purAmt = parseFloat(getItemValue("u_ave_amt")) || 0; // 市场平均金额
		return sqyjAmt - purAmt;
	}
	// // /10.表体数据变化（增行、删行、引入）时，汇总计算至表头
	// useUpdateRows(({ args }) => {
	// 	var sumAmt = 0;
	// 	const rows = args[0];
	// 	rows.forEach((items) => {
	// 		if (items.u_target_prc && items.u_qty) {
	// 			sumAmt += parseFloat(items.u_target_prc * items.u_qty);
	// 		}
	// 		//汇总赋值
	// 		$NG.updateState((updater) => {
	// 			updater.data.p_form_integrated_apply_m.setProps({
	// 				u_tar_amt: sumAmt,
	// 			});
	// 		});
	// 	});
	// }, "p_form_integrated_apply_d1");
});

//表体u_qty*u_pur_prc=表头u_pur_amt

//表体u_qty*u_prc=表头u_ave_amt



const style = document.createElement('style');  // 创建一个新的 <style> 元素
const cssRules = `
 
        .zdy-bigBox{
            background:white;
            width: 60vw;
            height:60vh;
            top:15vh;
            left:20vw;
            border-radius:4px;
        }
        .zdy-tableHeader{
            border-bottom:1px #d3d3d3 solid;
            padding:1vh 0 ;
            display:flex;
            justify-content: space-between;
        }
        .zdy-header-button{
            width:35%;
        }
        .zdy-header-button input{
            border:1px #d3d3d3 solid;
            border-radius: 4px;
            height:100%;
            width:80%;
            font-size:40%;
            outline: none;
            padding-left:2px;
        }
        .zdy-header-button button{
            width:2vw;
            height:2vw;
        }
        .zdy-title{
            border-left:4px #1677ff solid;
            padding:0 0 0 0.5vw ;
        }
        .header{
            display:flex;
        }
        /* tabs */
        .zdy-tabs-box{
            width:100%;
            height:8%;
            border:1px green solid;
        }
        .zdy-tabs-box ul{
            width:auto;
            height:100%;
            padding-left:2%;
            display:flex;
            list-style: none;
            font-size:90%;
            align-items:end;
        }
        .zdy-tabs-box li{
            height:auto;
            margin-right:10%;
            border-bottom:#1677ff solid 2px;
        }
        .zdy-table{
            width:100%;
            border-collapse: collapse;
            overflow:hidden;
            text-align:left;
            background:#fff;
        }
        .zdy-table-box{
            margin:1% auto;
            width:98%;
            height:80%;
            overflow-y:scroll;
        }
        .zdy-table tr{
            height: 30px;
            border-bottom:1px #d0d0d0 solid;
            /*border:1px black solid;*/
            transition: all 0.2s linear;
        }
        .zdy-table td,.zdy-table th{
            padding:1.5% 0;
            /*border:1px black solid;*/
        }
        .zdy-table-thead-tr,zdy-table-tbody-tr{
            vertical-align: top;
        }
        .zdy-table-thead-tr th{
            height:10px;
        }
        .zdy-col-box{
            width:100%;
            display:none;
            height:5%;
            ul{
                list-style: none;
                display:flex;
            }
        }
        .zdy-box-page{
            width:100%;
            display:flex;
        }
        .zdy-btn-ok{
            width:100%;
            height:5%;
            display:flex;
            justify-content: end;
        }
        .zdy-btn-ok button{
            margin-right:5%;
            width:6vw;
        }
        .zdy-btn-box{
            display:flex;
        }
            .zdy-active{
            background-color: hsl(215, 100%, 94%);
        }
            #zdy-main{
                background:#0000007a;
                width:100%;
                height:100vh;
                position:fixed;
                top:0;
                left:0;
                z-index:999;
                display:none;
                justify-content: center;
                align-items:center
            }
`;
style.textContent = cssRules;  // 设置 <style> 元素的内容为CSS规则字符串
document.head.appendChild(style); 


TestBody()
ajaxGet()
//关闭
function offT(){
    document.querySelector("#zdy-main").style.display = `none`
}
//开启
function onT(){
    document.querySelector("#zdy-main").style.display = `flex`
}
function TestBody(){
    let code = `
        <div id="zdy-main">
            <div class="zdy-bigBox" >
        <!-- 表头 start -->
        <div class="zdy-tableHeader">
            <h5 class="zdy-title">工作周期</h5>
            <div class="zdy-header-button">
                <input type="text" placeholder="请输入关键词">
                <button>X</button>
            </div>
        </div>
        <!-- 表头 end -->

        <!-- Tabs start -->
         <div class="zdy-col-box">
            <ul>
                <li>所有数据</li>
            </ul>
         </div>
         <!-- Tabs end -->

         <!-- 表体 start -->
          <div class="zdy-table-box">
              <table class="zdy-table" id="zdy-table">
                
                  
              </table>
          </div>
         <!-- 表体 end -->
<!--        分页控件 start-->
        <div class="zdy-col-box">
            <p>第1-20条/总共 70条</p>
            <div class="zdy-box-page">
                <button><</button>
                <ul>
                    <li>1</li>
                    <li>2</li>
                    <li>3</li>
                    <li>4</li>
                </ul>
                <button>></button>
            </div>
        </div>
        <!--        分页控件 end-->
        <div class="zdy-btn-ok">
           <div class="zdy-btn-box">
               <button id="zdy-btn-off">取消</button>
               <button id="zdy-btn-on">确定</button>
           </div>
        </div>
    </div>
        </div>
    `
    document.querySelector('#root').insertAdjacentHTML('beforeend',code)
    document.querySelector("#zdy-btn-off").addEventListener('click',(e)=>{
        offT()
        nodeActive.classList.remove('zdy-active')
        currentSeleRow = -1
    })
    //TODO 缺少字段
    document.querySelector("#zdy-btn-on").addEventListener('click',(e)=>{
        console.log(resData[currentSeleRow]);
        const _data = resData[currentSeleRow]
        if(currentSeleRow!==-1){
            $NG.updateState((updater)=>{
                updater.data.p_form_integrated_apply_m.setProps({
                    u_bus_no:_data.ProjectNo__c,
                    u_sj_name:_data.name,
                    u_tar_amt:_data.field_3blb1__c,
    
                })
            })
        }
        nodeActive.classList.remove('zdy-active')
        currentSeleRow = -1
        offT()
    })
}
// 请求服务器
function ajaxGet() {
	const xhr = new XMLHttpRequest();
	xhr.open(
		"POST",
		"http://nginx.clouddev.hisense.com/sd/sdToCrm/apply/opportunity/query"
	);
	xhr.setRequestHeader("Content-Type", "application/json");
	xhr.send(
		JSON.stringify({
			name: "guohairui.ex",
		})
	);
    let str = `
     <thead>
        <tr class="zdy-table-thead-tr">
            <th>商机编码</th>
            <th>商机名称</th>
            <th>项目金额</th>
            <th>售前</th>
            <th>预计签单时间</th>
        </tr>
    </thead>
    <tbody>
    `
	xhr.onreadystatechange = function () {
		if (xhr.readyState === 4 && xhr.status === 200) {
			var response = JSON.parse(xhr.responseText);
			console.log("服务器端返回的响应:", response);
            resData = response
            resData.forEach(item => {
                str+=`
                     <tr class="zdy-table-tbody-tr">
                        <td>${item.ProjectNo__c}</td>
                        <td>${item.name}</td>
                        <td>${item.field_3blb1__c}</td>
                        <td>${item.MainPerson_presales__c[0]}</td>
                        <td>${item.estimated_signing_time__c}</td>
                    </tr>
                `
            })
            str += "</tbody></table>"
            // document.querySelector("#zdy-table").addEventListener
            document.querySelector("#zdy-table").insertAdjacentHTML('beforeend', str)
            if(domTRarr){
                domTRarr.forEach(item=>{
                    item.removeEventListener('click', itemFC())
                })
            }
            domTRarr = document.querySelectorAll(".zdy-table-tbody-tr")
            domTRarr.forEach((item, index) => {
                item.addEventListener('click', (e)=>{
                    itemFC(e,index)
                })
                item.addEventListener('dblclick',()=>{
                    console.log(`双击事件`);
                    dbClick()
                    
                })
            })
		} else {
			console.log(`错误`);
		}
	};
    //双击触发事件
    function dbClick(){
        const _data = resData[currentSeleRow]
        currentSeleRow=-1
        document.querySelector("#zdy-main").style.display = `none`
        try{
            nodeActive.classList.remove('zdy-active')
        }catch(e){}
        $NG.updateState((updater)=>{
            updater.data.p_form_integrated_apply_m.setProps({
                u_bus_no:_data.ProjectNo__c,
                u_sj_name:_data.name,
                u_tar_amt:_data.field_3blb1__c
            })
        })
    }
    // 点击逻辑
    function itemFC(e, index){
        currentSeleRow = index
        console.log(e,'qf');
        if(e.target instanceof HTMLTableCellElement){
            const pre = e.target.parentNode
            if(pre instanceof HTMLTableRowElement){
                if(nodeActive){
                    nodeActive.classList.remove('zdy-active')
                }
                nodeActive = pre
                nodeActive.classList.add('zdy-active')
            }
        }
        
    }
}